import uuid
from django.views.decorators.http import require_POST, require_GET
import requests
import json
from rest_framework import status
from rest_framework.views import APIView

from order.jsonresp import JSONResponse
from order.pagedata import pageData
from rsa import decripta_data
from .models import Users
from .serializers import UserSerializer
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from rest_framework import status
from ..base.logMsg import logMsg


class UserList(APIView):
    def get(self, request):
        users = Users.objects.all().order_by("-id")
        page = request.GET.get('page', 1)
        limit = request.GET.get('limit', 20)
        ser, count = pageData(users, UserSerializer, page, limit)
        data = {'items': ser.data, 'total': count}
        return JSONResponse(code=0, data=data)

    def post(self, request):
        json_data = request.data.copy()
        json_data["id"] = str(uuid.uuid4())
        json_data['password'] = decripta_data(json_data['password'])
        serializer = UserSerializer(data=json_data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(code=0)
        return JSONResponse(10000, message=str(serializer.errors))


@require_POST
def login(request):
    json_data = json.loads(request.body)
    logMsg().info(str(json_data))
    username = json_data.get("username")
    password = json_data.get("password")
    openid = json_data.get("openid")
    try:
        password = decripta_data(password)
    except Exception as e:
        logMsg().info("pwd Error" + str(e))
        return JSONResponse(code=10000, message="登录异常")
    user_info = Users.objects.filter(username=username).first()
    if not user_info:
        return JSONResponse(code=10000, message="用户不存在")
    if user_info.password != password:
        return JSONResponse(code=10000, message="密码错误")
    user_info.openid = openid
    user_info.save()
    return JSONResponse(code=0, data={
        "user_id": user_info.id,
        "name": user_info.name,
        "username": username,
        "phone": user_info.phone,
        "email": user_info.email,
        "sex": user_info.sex
    })


@require_GET
def get_openid(request):
    code = request.GET.get('code')
    appid = "wxefb9f13917f7eca9"
    secret = "90a8cbeba423052532b07a5bfa1c31cd"
    requests_url = ("https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code"
                    .format(appid, secret, code))
    logMsg().info("get open_id url: " + str(requests_url))
    res = requests.get(requests_url)
    logMsg().info("get open_id detail: " + str(res.text))
    res = json.loads(res.text)
    if "errcode" in res and res["errcode"] != 0:
        return JSONResponse(code=10000, message={"errcode": res["errcode"], "errmsg": res["errmsg"]})
    openid = res["openid"]
    user_info = Users.objects.filter(openid=openid).first()
    return JSONResponse(code=0, data={
        "openid": openid,
        "user_id": user_info.id if user_info else None,
    })
